<template>
  <el-upload
      :file-list="fileList"
      list-type="picture-card"
      :data="dataObj"
      :before-upload="beforeUpload"
      :on-success="handleImageSuccess"
      drag
      action="https://gulimaill-hi.oss-cn-beijing.aliyuncs.com"
  >
    <el-icon>
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { getPolicy } from '@/api/product/oss.js'
import { Plus } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'SingleImageUpload',
  components: { Plus },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tempUrl: '',
      dataObj: {},
      fileList: []
    }
  },
  computed: {
    imageUrl() {
      return this.modelValue
    }
  },
  methods: {
    rmImage() {
      this.emitInput('')
    },
    emitInput( val ) {
      this.$emit('update:modelValue', val)
    },
    handleImageSuccess( res, file, fileList ) {
      const urls = fileList.map(f => `https://gulimaill-hi.oss-cn-beijing.aliyuncs.com/dir/${f.uid}${f.name}`)
      this.emitInput(urls.toString())
      this.fileList = fileList
    },
    async beforeUpload( file ) {
      const {
        policy,
        signature,
        dir,
        x_oss_security_token,
        x_oss_signature_version,
        x_oss_credential,
        x_oss_date
      } = await getPolicy()
      this.dataObj = {
        policy, 'x-oss-signature': signature,
        'x-oss-security-token': x_oss_security_token,
        'x-oss-signature-version': x_oss_signature_version, 'x-oss-credential': x_oss_credential,
        'x-oss-date': x_oss_date, success_action_status: 200,
        key: dir + '/' + file.uid + file.name
      }
      return true
    }
  }
})
</script>

<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  height: 115px;
  --el-upload-picture-card-size: 120px;
}

:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 120px;
}
</style>
